package com.le.tester.book.concurrentchallenge.cancelclose;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * createTime：2025-04-02 10:08
 * description：使用volatile类型的域来保存取消状态，（可见性）
 */
public class PrimeGenerator implements Runnable {

    public final ExecutorService es = Executors.newCachedThreadPool();

    private final List<BigInteger> priList = new ArrayList<>();

    private volatile boolean canceled;

    @Override
    public void run() {
        BigInteger one = BigInteger.ONE;
        while (!canceled) {
            //生成下一个素数
            BigInteger bigInteger = one.nextProbablePrime();
            System.out.println(bigInteger);
            synchronized (this) {
                priList.add(bigInteger);
            }
        }
    }

    public void cancel() {
        canceled = Boolean.TRUE;
    }

    public synchronized List<BigInteger> get() {
        return new ArrayList<>(priList);

    }

    public static void main(String[] args) throws InterruptedException {
        PrimeGenerator primeGenerator = new PrimeGenerator();
        ExecutorService executorService = Executors.newCachedThreadPool();
        Future<?> submit = executorService.submit(primeGenerator);
        Thread.sleep(1000);
        primeGenerator.cancel();

        if (primeGenerator.canceled) {
            submit.cancel(true);
            executorService.shutdownNow();
//            System.exit(1);
        }

    }
}
